import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../widgets/platform/adaptive_card.dart';
import '../../widgets/platform/adaptive_button.dart';
import 'package:go_router/go_router.dart';
import '../../../data/services/data_management_service.dart';

/// 数据库表选择页面
/// 允许用户从已连接的数据库中选择表进行操作
class TableSelectionPage extends ConsumerStatefulWidget {
  final Map<String, dynamic> connectionConfig;

  const TableSelectionPage({super.key, required this.connectionConfig});

  @override
  ConsumerState<TableSelectionPage> createState() => _TableSelectionPageState();
}

class _TableSelectionPageState extends ConsumerState<TableSelectionPage> {
  List<String> _tables = [];
  List<String> _selectedTables = [];
  bool _isLoading = false;
  String? _error;

  @override
  void initState() {
    super.initState();
    _loadTables();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: SelectableText('${widget.connectionConfig['name']} - 表选择'),
        backgroundColor: Colors.blue.shade50,
        foregroundColor: Colors.blue.shade700,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.of(context).pop(),
        ),
      ),
      body: _buildContent(),
    );
  }

  Widget _buildContent() {
    if (_isLoading) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(),
            SizedBox(height: 16),
            SelectableText('正在加载表列表...'),
          ],
        ),
      );
    }

    if (_error != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.error_outline,
              size: 64,
              color: Colors.red,
            ),
            const SizedBox(height: 16),
            SelectableText(
              _error!,
              style: const TextStyle(color: Colors.red),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: _loadTables,
              child: const SelectableText('重试'),
            ),
          ],
        ),
      );
    }

    return _buildTableList();
  }

  Widget _buildTableList() {
    return Column(
      children: [
        // 工具栏
        _buildToolbar(),

        const SizedBox(height: 16),

        // 表列表
        Expanded(
          child: _tables.isEmpty ? _buildEmptyState() : _buildTableListView(),
        ),

        // 底部操作按钮
        if (_selectedTables.isNotEmpty) _buildBottomActions(),
      ],
    );
  }

  Widget _buildToolbar() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Row(
        children: [
          SelectableText(
            '数据库表 (${_tables.length})',
            style: const TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          const Spacer(),
          if (_tables.isNotEmpty)
            TextButton(
              onPressed: _toggleSelectAll,
              child: SelectableText(
                _selectedTables.length == _tables.length ? '取消全选' : '全选',
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildEmptyState() {
    return Center(
      child: AdaptiveCard(
        margin: const EdgeInsets.all(32),
        child: Padding(
          padding: const EdgeInsets.all(32),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Icon(
                Icons.table_chart,
                size: 64,
                color: Colors.grey,
              ),
              const SizedBox(height: 16),
              const SelectableText(
                '暂无数据表',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.w500,
                ),
              ),
              const SizedBox(height: 8),
              SelectableText(
                '该数据库中没有找到任何表',
                style: TextStyle(
                  color: Colors.grey.shade600,
                ),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 24),
              ElevatedButton(
                onPressed: _loadTables,
                child: const SelectableText('重新加载'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildTableListView() {
    return ListView.builder(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      itemCount: _tables.length,
      itemBuilder: (context, index) {
        final tableName = _tables[index];
        final isSelected = _selectedTables.contains(tableName);

        return Card(
          margin: const EdgeInsets.only(bottom: 12),
          child: ListTile(
            leading: Icon(
              isSelected ? Icons.check_box : Icons.check_box_outline_blank,
              color: isSelected ? Colors.blue : Colors.grey,
            ),
            title: SelectableText(
              tableName,
              style: TextStyle(
                fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
              ),
            ),
            trailing: const Icon(Icons.arrow_forward_ios, size: 16),
            onTap: () => _toggleTableSelection(tableName),
            onLongPress: () {
              _toggleTableSelection(tableName);
              // 长按后直接打开表
              _openSelectedTables();
            },
          ),
        );
      },
    );
  }

  Widget _buildBottomActions() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withValues(alpha: 0.2),
            blurRadius: 4,
            offset: const Offset(0, -2),
          ),
        ],
      ),
      child: Row(
        children: [
          SelectableText('${_selectedTables.length} 个表已选择'),
          const Spacer(),
          AdaptiveButton(
            onPressed: _openSelectedTables,
            isPrimary: true,
            child: const SelectableText('打开表'),
          ),
        ],
      ),
    );
  }

  /// 打开选中的表
  void _openSelectedTables() {
    if (_selectedTables.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: SelectableText('请至少选择一个表'),
          backgroundColor: Colors.orange,
        ),
      );
      return;
    }

    // 对于NocoDB风格的实现，我们只打开第一个选中的表
    // 在实际应用中，可能需要支持多表视图或标签页
    final tableName = _selectedTables.first;

    // 导航到智能电子表格页面
    context.push('/spreadsheet/$tableName', extra: {
      'connectionConfig': widget.connectionConfig,
      'tableName': tableName,
    });
  }

  /// 加载数据库表列表
  Future<void> _loadTables() async {
    setState(() {
      _isLoading = true;
      _error = null;
    });

    try {
      // 使用数据管理服务加载表列表
      final dataManagementService = DataManagementService();
      _tables =
          await dataManagementService.getTableList(widget.connectionConfig);

      setState(() {
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _error = '加载表列表失败: ${e.toString()}';
        _isLoading = false;
      });
    }
  }

  /// 切换表选择状态
  void _toggleTableSelection(String tableName) {
    setState(() {
      if (_selectedTables.contains(tableName)) {
        _selectedTables.remove(tableName);
      } else {
        _selectedTables.add(tableName);
      }
    });
  }

  /// 全选/取消全选
  void _toggleSelectAll() {
    setState(() {
      if (_selectedTables.length == _tables.length) {
        _selectedTables.clear();
      } else {
        _selectedTables = List.from(_tables);
      }
    });
  }
}
